<template>
  <div class="flex flex-col h-full">
    <a-card>
      <div class="flex justify-between items-center">
        <a-button type="primary" class="mr-4" @click="router.go(-1)"> 返回 </a-button>
        <a-descriptions class="mt-3" :column="4">
          <a-descriptions-item label="单号" class="w-1/3"> {{ formState?.rkdh || '-' }}</a-descriptions-item>
          <a-descriptions-item label="入库日期" class="w-1/3"> {{ formState?.rksj || '-' }}</a-descriptions-item>
          <a-descriptions-item label="入库仓库" class="w-1/3"> {{ formState?.ckmc || '-' }}</a-descriptions-item>
          <a-descriptions-item label="供应商" class="w-1/3"> {{ formState?.gysmc || '-' }}</a-descriptions-item>
          <a-descriptions-item label="发票状态" class="w-1/3"> {{ formState?.fpzt == 0 ? '普通' : '在途' }}</a-descriptions-item>
          <a-descriptions-item label="发票号" class="w-1/3"> {{ formState?.fph || '-' }}</a-descriptions-item>
          <a-descriptions-item label="制单人" class="w-1/3"> {{ formState?.createUser }}</a-descriptions-item>
          <a-descriptions-item label="发票日期" class="w-1/3"> {{ formState?.createTime || '-' }}</a-descriptions-item>
        </a-descriptions>
      </div>
    </a-card>
    <a-card class="mt-2 flex-1">
      <BaseTable
        :data-source="dataSource"
        max-fill
        :extra-height="64"
        column-code="000144"
        row-key="lsh"
        :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
          <template v-if="column.dataIndex === 'rklb'">
            <EditCell title="类别">
              <SelectItem
                v-model:value="record.rklbmc"
                type="DT00290"
                trigger="focus"
                placeholder="请选择"
                @blur="onInputfocus(record)"
                @select="selectDict($event, record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'ypmc'">
            <EditCell title="物品名称">
              <SelectMedicine :value="{ mc: record.ypmc, gg: record.gg, cj: record.cj }" type="物资采购" @select="onSelectMedicine($event, record)" />
              <!-- <SelectTable v-model:value="record.ypmc" type="采购" @select="(medicine) => onSelectMedicine(record, medicine)" /> -->
            </EditCell>
          </template>
          <!-- <template v-if="column.dataIndex === 'pzwh'">
            <EditCell title="批准文号">
              <a-input v-model:value="record.pzwh" placeholder="请输入" @blur="onInputfocus(record)" />
            </EditCell>
          </template> -->
          <template v-if="column.dataIndex === 'ph'">
            <EditCell title="批号">
              <BaseInput v-model:value="record.ph" :auto-focus="focusCell === record.key" placeholder="请输入" @blur="onInputfocus(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'scrq'">
            <EditCell title="生产日期">
              <a-date-picker
                v-model:value="record.scrq"
                :disabled-date="disabledDate"
                value-format="YYYY-MM-DD"
                placeholder="请输入"
                @keydown.enter="onDateEnter($event, record, 'scrq')"
                @change="onInputfocus(record, true)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'yxq'">
            <EditCell title="有效期">
              <a-date-picker
                v-model:value="record.yxq"
                value-format="YYYY-MM-DD"
                placeholder="请输入"
                @keydown.enter="onDateEnter($event, record, 'yxq')"
                @change="onInputfocus(record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'sl'">
            <EditCell title="数量">
              <a-input v-model:value="record.sl" class="text-right" placeholder="请输入" @change="onChangeCompute(record)" @blur="onInputfocus(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'dj'">
            <EditCell title="入库单价">
              <a-input
                v-model:value="record.dj"
                v-input:format.5
                placeholder="请输入"
                class="text-right"
                @change="onChangeCompute(record)"
                @blur="onInputfocus(record)"
              />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'cmemo'">
            <EditCell title="备注">
              <a-input v-model:value="record.cmemo" placeholder="请输入" @blur="onInputfocus(record)" />
            </EditCell>
          </template>
          <template v-if="column.dataIndex === 'isQualified'">
            <a-switch v-model:checked="record.isQualified" un-checked-value="2" checked-value="1" @change="onInputfocus(record)" />
          </template>
          <template v-if="column.dataIndex === 'action'">
            <a-button type="text" danger size="small" :disabled="formState?.status" @click="onDel(record)">删除</a-button>
          </template>
        </template>
        <template #footer>
          <div class="text-center sticky bottom-0">
            <a-button class="mr-2" type="primary" ghost @click="addRow()"> 新增一行 </a-button>
            <a-button type="primary" :disabled="dataSource.length === 0" @click="saveNewRows()"> 保存 </a-button>
            <a-button class="ml-2" @click="openImport = true"> 导入 </a-button>
          </div>
        </template>
      </BaseTable>
    </a-card>
    <a-modal v-model:open="openImport" title="导入数据" :footer="false" centered>
      <p>须确保导入的文件格式是csv</p>
      <div class="flex justify-end mt-16">
        <a-button class="mr-2"> 下载模版 </a-button>
        <a-button type="primary"> 导入 </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import BaseTable from '@/components/BaseTable'
import { post } from '@/utils/request'
import EditCell from '@/components/EditCell'

const route = useRoute()
const router = useRouter()
const formState = ref({})
const focusCell = ref('')
const openImport = ref(false)
const onInputfocus = async (res, flag) => {
  // return
  if (flag) {
    const { data, code, msg } = await post('/materials/psiform/getMtrCgmxbScrqResponse', {
      ypbh: res.ypbh,
      scrq: res.scrq
    })
    if (code !== 0) return message.error(msg)
    res.yxq = data?.yxq
    editRow({ ...res, yxq: data?.yxq })
  } else {
    editRow(res)
  }
}
const getMainData = async () => {
  const { data, code } = await post('/materials/psiform/getWarehousingHeadList', {
    dhmc: route.query.rkdh || ''
  })
  if (code === 0) {
    formState.value = data[0]
  }
  getData()
}
const loading = ref(false)

const dataSource = ref([])

const onDel = async (record) => {
  if (record.rkdh) {
    const { code, msg } = await post('/materials/psiform/doDeleteWarehousingDetai', { dh: route.query.rkdh || '', lsh: record.lsh })
    if (code !== 0) {
      message.error(msg)
    }
    message.success(msg)
    dataSource.value = dataSource.value.filter((item) => item.key !== record.key)
    getData()
  } else {
    dataSource.value = dataSource.value.filter((item) => item.key !== record.key)
  }
}

const onChangeCompute = (record) => {
  if (record.sl && parseFloat(record.dj)) {
    record.je = (record.sl * parseFloat(record.dj)).toFixed(2)
  } else {
    record.je = 0
  }
}

const editRow = (row) => !row.isNew && fetchSave(row)
const fetchSave = async (row, callBack) => {
  if (!row.ph) return message.error(row.ypmc + '的批号不能为空')
  const rows = {
    rkdh: formState.value.rkdh || '',
    ...row
  }
  const { code, msg } = await post('/materials/psiform/doSaveWarehousingDetail', rows)
  if (code !== 0) return message.error(msg || '操作失败')
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
  getData()
  callBack()
}
const onSelectMedicine = (medicine, row) => {
  // row.sfxmb = medicine
  row.sl = 1
  row.bh = medicine.bh
  row.ypbh = medicine.bh
  row.gg = medicine.gg
  row.dw = medicine.dw
  row.zxdwsl = 1
  row.ypmc = medicine.mc
  row.ypbh = medicine.bh
  row.cj = medicine.cj
  row.isQualified = '1'
  row.jlsl = row.zxdwsl * medicine?.jldwzsb || 0
  focusCell.value = row.key
  editRow(row)
}
//添加行
const addRow = async () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true, addtime: dayjs().format('YYYY-MM-DD HH:mm:ss') }
  dataSource.value.push(addRow)
}

const getData = async () => {
  loading.value = true
  const { data, code } = await post('/materials/psiform/getWarehousingDetailList', {
    rkdh: formState.value.rkdh || '',
    pageNum: 1,
    pageSize: 999
  })
  loading.value = false
  if (code === 0) {
    dataSource.value = data.map((item) => {
      item.dj = item?.dj ? item?.dj.toFixed(5) : ''
      item.je = item?.je ? item?.je.toFixed(2) : ''

      return item
    })
  }
}
const saveNewRows = async () => {
  const newRow = dataSource.value.filter((item) => item.isNew)
  for (const item of newRow) {
    if (item.ypbh && item.sl) {
      await new Promise((resolve) => {
        fetchSave(item, () => {
          resolve()
        })
      })
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  }
  // newRow.forEach((item) => {
  //   if (item.ypbh && item.sl) {
  //     fetchSave(item)
  //   } else {
  //     message.destroy()
  //     message.error('请填写完整信息')
  //   }
  // })
}

const selectDict = (val, row) => {
  row.rklb = val
}

const disabledDate = (current) => {
  // 获取今天的日期
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  // 将当前日期与今天的日期进行比较
  return current && current >= today
}
watchEffect(() => {
  if (route.query?.rkdh) {
    getMainData()
  }
})
const onDateEnter = (e, row, key) => {
  const dateString = e.target.value
  const regex1 = /^\d{8}$/ // 匹配YYYYMMDD格式
  const regex2 = /^\d{4}-\d{2}-\d{2}$/ // 匹配YYYY-MM-DD格式
  const regex3 = /^\d{4}\/\d{2}\/\d{2}$/ // 匹配YYYY/MM/DD格式
  const regex4 = /^\d{4}\.\d{2}\.\d{2}$/ // 匹配YYYY.MM.DD格式
  // 检查日期字符串是否符合任何一个正则表达式
  const isValidDate = regex1.test(dateString) || regex2.test(dateString) || regex3.test(dateString) || regex4.test(dateString)
  if (isValidDate) {
    row[key] = dayjs(dateString).format('YYYY-MM-DD')
    e.target.blur()
  }
}
</script>
<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
